<?php

class Admin_PostController extends ExtLb_Controller_Action
{

	private $postTbl ;
	private $menu2Tbl;
	private $frmBaiViet;
	
	private $auth;
	private $storageAuth;
	
    public function init()
    {
        $this->loadLayout('admin', 'layout');
        $this->loadCss('admin', 'post', FOLDER_ROOT_NAME);
        
        $this->postTbl		= new Admin_Model_Posts();
        $this->menu2Tbl		= new Admin_Model_Menu2();
        $this->frmBaiViet	= new Admin_Form_Post();
        
        $this->auth			= Zend_Auth::getInstance();
        $this->storageAuth	= $this->auth->getIdentity();
        
        date_default_timezone_set('Asia/Ho_Chi_Minh');
    }

    public function indexAction()
    {
    	if($this->storageAuth->quyen == "admin"){
	    	if(isset($_GET['search_box_sumit']) && !empty($_GET['search_box_text'])){
	    		$selectPost = $this->postTbl->selectPost("tieuDe like '%".$_GET['search_box_text']."%'");
	    	}else{
	    		$selectPost = $this->postTbl->selectPost();	
	    	}
	        
	    	//
	    	//FILTER
	    	if(isset($_GET['tbn_filter']) && (int)$_GET['tbn_cate'] != 0){
	    		$selectPost = $this->postTbl->selectPost("bv.menu2Id = ".$_GET['tbn_cate']);
	    	}
	    	
	        $paginator	= new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($selectPost));
	        $paginator->setItemCountPerPage(20)
	        			->setPageRange(3)
	        			->setCurrentPageNumber($this->_getParam('page',1));
	        
	      	$this->view->paginatorPosts	= $paginator;
	      	$this->view->menu2s = $this->menu2Tbl->fetchColMenu2(array('menu2Id', 'tenMenu2'));
	      	
	    	//
	    	//FORWARD TO DETETEACTION
	    	if(isset($_GET['cmdDel']) && !empty($_GET['post-check'])){
	  			$this->_forward('delete','post','admin');
	    	}
    	}else{//not admin
	    	if(isset($_GET['search_box_sumit']) && !empty($_GET['search_box_text'])){
	    		$selectPost = $this->postTbl->selectPost("tieuDe like '%".$_GET['search_box_text']."%' and 
	    													bv.tenDangNhap ='".$this->storageAuth->tenDangNhap."'"
	    									);
	    	}else{
	    		$selectPost = $this->postTbl->selectPost("bv.tenDangNhap = '".$this->storageAuth->tenDangNhap."'");	
	    	}
	        
	    	//
	    	//FILTER
	    	if(isset($_GET['tbn_filter']) && (int)$_GET['tbn_cate'] != 0){
	    		$selectPost = $this->postTbl->selectPost("bv.menu2Id = ".$_GET['tbn_cate']
	    													." and bv.tenDangNhap ='".$this->storageAuth->tenDangNhap."'"
	    									);
	    	}
	    	
	        $paginator	= new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($selectPost));
	        $paginator->setItemCountPerPage(20)
	        			->setPageRange(3)
	        			->setCurrentPageNumber($this->_getParam('page',1));
	        
	      	$this->view->paginatorPosts	= $paginator;
	      	$this->view->menu2s = $this->menu2Tbl->fetchColMenu2(array('menu2Id', 'tenMenu2'));
	      	
	    	//
	    	//FORWARD TO DETETEACTION
	    	if(isset($_GET['cmdDel']) && !empty($_GET['post-check'])){
	  			$this->_forward('delete','post','admin');
	    	}
    	}
    	
      	
    }

    public function addAction()    {
    	//
    	//LOAD DATA TO EDIT
    	if(isset($_GET['edit']) && !empty($_GET['post'])){
    		$this->frmBaiViet->addAction('admin', 'post', 'edit');
    		$this->frmBaiViet->addSubmitButton('cmdEdit', 'Cập nhập');
    		
    		//LAY DU DIEU LOAD LEN FORM
    		$post = $this->postTbl->fetchRowPost($_GET['post']);
    		
    		//SET DU LIEU CHO FORM
    		$this->frmBaiViet->addHiddenId('postId', $post['baiVietId']);
    		$this->frmBaiViet->getElement('txtTieuDe')->setValue($post['tieuDe']);
    		$this->frmBaiViet->getElement('fHinh')->setValue($post['hinh']);
    		$this->frmBaiViet->getElement('tAreaNoiDung')->setValue($post['noiDung']);
    		$this->frmBaiViet->getElement('cbbMenu2')->setValue($post['menu2Id']);
    		$this->frmBaiViet->getElement('cbbTrangThai')->setValue($post['trangThai']);
    		//
    		$this->frmBaiViet->addHiddenId('fImg', $post['hinh']);
    		
    	}else{
        
	        $this->frmBaiViet->addAction('admin', 'post', 'add');
	        $this->frmBaiViet->addSubmitButton('cmdAdd', 'Thêm bài viết');
	        
	        //
	        //ADD POST
	        if (isset($_POST['cmdAdd'])){
		        if($this->frmBaiViet->isValid($this->_request->getPost())){
		        	
		        	$tieuDe 	= $this->_getParam('txtTieuDe');
		        	if (!empty($_POST['fImg'])){
		        		$hinh = $_POST['fImg'];
		        	}else{
		        		$hinh 		= isset($_FILES['fHinh']['name']) && !empty($_FILES['fHinh']['name'])? $_FILES['fHinh']['name'] : " ";
		        	}
		        	
//			        if (file_exists(WEB_ROOT."/public/upload/images/" . $_FILES["fHinh"]["name"])){
//			            echo $_FILES["fHinh"]["name"] . "<br /><strong>Hình này đã tồn tại.</strong> ";
////			        }elseif(!empty($hinh) || $hinh != " " || $hinh !=""){
	
		        	if (!empty($hinh)){
			            move_uploaded_file($_FILES["fHinh"]["tmp_name"],WEB_ROOT."/public/upload/images/". $hinh);
			        }
			        	
		        	$noiDung 	= $this->_getParam('tAreaNoiDung');
		        	$menu2Id 	= $this->_getParam('cbbMenu2');
		        	$trangThai 	= trim($this->_getParam('cbbTrangThai'));
		        	$now = getdate();
		        	
		        	//PHAI LAM XU LY LAY TEN DANG NHAP
		        	$tenDangNhap = $this->storageAuth->tenDangNhap;
		        	
		        	$ngayViet = $now['mday']."/".$now['mon']."/".$now['year'];
		
		        	try {
		        		$this->postTbl->addPost($tieuDe, $hinh, $noiDung, $ngayViet, $menu2Id,$trangThai, $tenDangNhap);	
		        		$this->jDialogMessage("Thông báo","Thành công!!!" );
		        	} catch (Exception $e) {
		        		$this->jDialogMessage("Thông báo","Có lỗi xảy ra trong quá trình xử lý. Hãy thử lại!!.");
		        	}
		        	
		        	$this->_forward('index','post','admin');
		        }
	        }
	    }
    	
    	$this->view->frmBaiViet = $this->frmBaiViet;
    	
   		 //
    	//FORWARD TO DETETEACTION
    	if(isset($_GET['cmdDel']) && !empty($_GET['post-check'])){
  			$this->_forward('delete','post','admin');
    	}
    }

    public function editAction(){
	    //
    	//FILTER
    	if(isset($_GET['tbn_filter']) && (int)$_GET['tbn_cate'] != 0){
    		$selectPost = $this->postTbl->selectPost("bv.menu2Id = ".$_GET['tbn_cate']);
    		$this->_forward('index','post','admin');
    	}
	    	
        if($this->frmBaiViet->isValid($this->_request->getPost())){
        	if(isset($_POST['cmdEdit'])){
        		try {
        			$tieuDe 	= $this->_getParam('txtTieuDe');
	        		if (!empty($_POST['fImg']) && empty($_FILES['fHinh']['name'])){
			        	$hinh = $this->_getParam('fImg');
			        }else{
			        	$hinh 		= isset($_FILES['fHinh']['name']) && !empty($_FILES['fHinh']['name'])? $_FILES['fHinh']['name'] : " ";
			        	move_uploaded_file($_FILES["fHinh"]["tmp_name"],WEB_ROOT."/public/upload/images/". $hinh);
			        }
		        	$noiDung 	= $this->_getParam('tAreaNoiDung');
		        	$menu2Id 	= $this->_getParam('cbbMenu2');
		        	$trangThai 	= trim($this->_getParam('cbbTrangThai'));
		        	$now = getdate();
		        	
		        	//PHAI LAM XU LY LAY TEN DANG NHAP
		        	$tenDangNhap = "admin";
		        	
		        	$ngayViet  = $now['mday']."/".$now['mon']."/".$now['year'];
		        	$baiVietId = $this->_getParam('postId');
		        	
		        	$this->postTbl->updatePost($tieuDe, $hinh, $noiDung, $ngayViet, $menu2Id,$trangThai, $tenDangNhap, $baiVietId);
		        	$this->jDialogMessage("Thông báo","Thành công!!!");	
		        	
        		} catch (Exception $e) {
        			$this->jDialogMessage("Thông báo","Có lỗi xảy ra trong quá trình xử lý. Hãy thử lại!!.");
        		}
        		
	        	
	        	$this->_forward('index','post','admin');
        	}
        }else{
        	$this->_redirect("/admin/post/");
        }
    }

    public function deleteAction(){
	    //
    	//FILTER
    	if(isset($_GET['tbn_filter']) && (int)$_GET['tbn_cate'] != 0){
    		$this->_forward('index','post','admin');
    	}
    	//
    	//MOVE TRASH
        if(isset($_GET['trash']) && !empty($_GET['post'])){
        	try {
        		$this->postTbl->updateCustomPost(
        						array('thungRac' => '1','trangThai' => '0'), 
        						"baiVietId =".$_GET['post']
        					);
        		
        	} catch (Exception $e) {
        		$this->jDialogMessage("Thông báo","Có lỗi xảy ra trong quá trình xử lý. Hãy thử lại!!.");
        	}
        	
        	$this->_redirect('/admin/post/');
        }
        
        //
        //RESTORE
        if(isset($_GET['restore']) && !empty($_GET['post'])){
        	try {
        		$this->postTbl->updateCustomPost(array('thungRac'=>'0'), 'baiVietId ='.$_GET['post']);	
        	} catch (Exception $e) {
        		$this->jDialogMessage("Thông báo","Có lỗi xảy ra trong quá trình xử lý. Hãy thử lại!!.");
        	}
        	
        	$this->_redirect('/admin/post/');
        }
        
        //
        //DELETE 1 RECORD
        if (isset($_GET['delete']) && !empty($_GET['post'])) {
        	try {
        		$this->postTbl->deletePost($_GET['post']);	
        	} catch (Exception $e) {
        		$this->jDialogMessage("Thông báo","Có lỗi xảy ra trong quá trình xử lý. Hãy thử lại!!.");
        	}
        	
        	if(isset($_GET['viewtrash'])){
        		$this->jShowMessage("Thành công!!!");
        		$this->_forward('viewtrash','post','admin');
        	}else{
        		
        		$this->jDialogMessage("Thông báo", "Thành công!!!");
        		$this->_forward('index','post','admin');
        	}
        }
        
        //
        //DELETE MULTI
        if(isset($_GET['cmdDel']) ){
        	try {
	        	$arrDataDel = $_GET['post-check'];
	        	for ($i =0; $i< count($arrDataDel); $i++ ){
	        		$this->postTbl->deletePost($arrDataDel[$i]);
	        	}	
        	} catch (Exception $e) {
        		$this->jDialogMessage("Thông báo","Có lỗi xảy ra trong quá trình xử lý. Hãy thử lại!!.");
        	}
        	
        	$this->_redirect('/admin/post/');
        }
    }

    public function viewtrashAction(){
    	if(isset($_GET['search_box_sumit']) && !empty($_GET['search_box_text'])){
    		$selectPost = $this->postTbl->selectPost("tieuDe like '%".$_GET['search_box_text']."%'");
    	}else{
    		$selectPost = $this->postTbl->selectPost();	
    	}
        
	    //
    	//FILTER
    	if(isset($_GET['tbn_filter']) && (int)$_GET['tbn_cate'] != 0){
    		$selectPost = $this->postTbl->selectPost("bv.menu2Id = ".$_GET['tbn_cate']);
    	}
    	
        $paginator	= new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($selectPost));
        $paginator->setItemCountPerPage()
        			->setPageRange(3)
        			->setCurrentPageNumber($this->_getParam('page',1));
        
      	$this->view->paginatorPosts	= $paginator;
      	$this->view->menu2s = $this->menu2Tbl->fetchColMenu2(array('menu2Id', 'tenMenu2'));
      	
	    //
    	//FORWARD TO DETETEACTION
    	if(isset($_GET['cmdDel']) && !empty($_GET['post-check'])){
  			$this->_forward('delete','post','admin');
    	}
    }

    public function publishAction(){
    	if(isset($_GET['up']) && !empty($_GET['post'])){
    		
    		try {
    			$post = $this->postTbl->fetchCol(array('thungRac'),'baiVietId ='.$_GET['post']);
	    		
	    		if($post[0]['thungRac'] == 1){
	    			$this->postTbl->updateCustomPost(array('thungRac'=>'0'), 'baiVietId ='.$_GET['post']);
	    		}
	    		$this->postTbl->updateCustomPost(array('trangThai'=> '1'), "baiVietId =".$_GET['post']);
	    		
	    		$this->jDialogMessage("Thông báo", "Bài viết đã được đăng!!!");
	    			
    		} catch (Exception $e) {
    			$this->jDialogMessage("Thông báo","Có lỗi xảy ra trong quá trình xử lý. Hãy thử lại!!.");
    		}
    		
    		$this->_forward('index','post','admin');
    	}
    	
    	if(isset($_GET['down']) && !empty($_GET['post'])){
    		
    		try {
    			$post = $this->postTbl->fetchCol(array('thungRac'),'baiVietId ='.$_GET['post']);
    		
	    		if($post[0]['thungRac'] == 1){
	    			$this->postTbl->updateCustomPost(array('thungRac'=>'0'), 'baiVietId ='.$_GET['post']);
	    		}
	    		$this->postTbl->updateCustomPost(array('trangThai'=> '0'), "baiVietId =".$_GET['post']);
	    		
	    		$this->jDialogMessage("Thông báo","Đã hủy đăng đăng bài!!!");
	    			
    		} catch (Exception $e) {
    			$this->jDialogMessage("Thông báo","Có lỗi xảy ra trong quá trình xử lý. Hãy thử lại!!.");
    		}
    		
    		$this->_forward('index','post','admin');
    	}
    }
}







